<script setup>
import {ref,onMounted,watch} from 'vue'
//import monaco from '../lib/vs/editor/editor.main.js'
import require from  "require";


require.config({ paths: { vs: 'lib/vs' } });

//import * as monaco from 'https://cdn.jsdelivr.net/npm/monaco-editor@0.47.0/+esm'
const editor=ref(null)
let monacoEditor=null
const emit=defineEmits(['save','change','update:modelValue'])
const props=defineProps({
  modelValue: String,
  language:{
    default:'javascript'
  },
  value:{
    default:' '
  },
  options:{
    default:function () {
      return {
        automaticLayout:true
      }
    }
  }
})
async function initEditor(){
  let monaco = await require('vs/editor/editor.main')
    let opt= props.options;
    opt.value=props.modelValue;
    opt.language=props.language
    monacoEditor = monaco.editor.create(editor.value,opt);
    monacoEditor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, (v)=> {
      emit("save",monacoEditor.getValue())
    })
    monacoEditor.getModel().onDidChangeContent((event) => {
      let v=monacoEditor.getValue()
      emit("update:modelValue",v)
      emit("change",v)
    });
}
function save(){
  emit("save",monacoEditor.getValue())
}
let registered=false
onMounted(()=>{
  let language=props.language;
  if(!registered&&language=='nginx'){
    registered=true
    require('vs/language/nginx/nginx.js').then((r)=>{
      r.register(monaco);
      initEditor()
    })
  }else{
    initEditor()
  }
})
watch(()=>props.modelValue,(v,per)=>{
  if(monacoEditor){
    let cv=monacoEditor.getValue()
    if(cv!=v){
      monacoEditor.getModel().setValue(v);
    }
  }
})
defineExpose({save})
</script>

<template>
  <div ref="editor"></div>
</template>
